package com.yingda.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;

import com.hjq.toast.ToastUtils;
import com.yingda.server.MyForegroundService;
import com.yingda.utils.SendMessageUtils;
import com.yingda.utils.SharedPreferenceUtil;

public class SmsReceiver extends BroadcastReceiver {

    private static final String TAG = "SmsReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        //获取本人的手机号
        String defaultPhone = SharedPreferenceUtil.getInstance(context).getString("defaultPhone");
        String newPhone = SharedPreferenceUtil.getInstance(context).getString("newPhone");

        if (bundle != null) {
            // 从 Bundle 中提取短信消息
            Object[] pdus = (Object[]) bundle.get("pdus");
            if (pdus != null) {
                for (Object pdu : pdus) {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
                    String sender = smsMessage.getDisplayOriginatingAddress();  // 获取发送者号码
                    String messageBody = smsMessage.getMessageBody();           // 获取短信内容
                    long timestampMillis = smsMessage.getTimestampMillis();     // 获取发送时间

                    Log.d(TAG, "Sender: " + sender + ", Message: " + messageBody +"发送时间：" + timestampMillis);
                    // 在此处可以实现后续逻辑处理，比如展示通知等
                    ToastUtils.show("Sender: " + sender + ", Message: " + messageBody +"发送时间：" + timestampMillis);
                    if (TextUtils.isEmpty(defaultPhone)){
                        ToastUtils.show("请先点击获取手机号接收短信");
                        return;
                    }
                    SendMessageUtils.getInstance().setMessage(sender,messageBody,defaultPhone);
                    if (!TextUtils.isEmpty(newPhone)){
                        SendMessageUtils.getInstance().setMessage(sender,messageBody,newPhone);
                    }
                }
            }
        }
    }
}
